const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const { NodeSSH } = require('node-ssh');

// 正确设置本地dist文件路径
const distPath = path.resolve(__dirname, '../dist');

const ssh = new NodeSSH();

// 获取远程服务器配置信息 此处建议通过配置文件获取
const config = {
  host: '36.133.150.224:22',
  pathUrl: '/opt/webapp/mall4cloud-multishop',    // 远程存放文件地址
};

// =============第三步===========执行远程部署命令
const remoteServiceUpdate = () => {
  // ssh.execCommand 在指定文件夹下执行了命令 sh upgrade.sh 
  // 此处请根据个人情况处理，此处只是给各位看官打个样~
  ssh.execCommand('sh upgrade.sh', { cwd: config.pathUrl }).then((result) => {
    console.log(`The update message is: ${result.stdout}`);
    if (!result.stderr) {
      console.log('Gratefule! update success!');
      process.exit(0);
    } else {
      console.log('Something wrong:', result);
      process.exit(0);
    }
  });
};

// =============第二步===========本地文件上传至远程服务器
function uploadFile() {
  ssh.connect({
    host: config.host,
    username: 'root',
    privateKey: `${process.env.HOME}/.ssh/id_rsa`,
  }).then(() => {
    console.log('SSH login success');
    // 上传网站的发布包至configs中配置的远程服务器的指定地址
    ssh.putFile(`${__dirname}/../dist.zip`, `${config.pathUrl}/dist.zip`).then(() => {
      console.log('The zip file is upload successful');
      remoteServiceUpdate();// 上传成功后触发远端脚本
    }).catch((err) => {
      console.log('the file upload fail:', err);
      process.exit(0);
    });
  }).catch((err) => {
    console.log('SSH conneting fail:', err);
    process.exit(0);
  });
}

// =============第一步===========本地文件压缩
const zipDirector = () => {
  const output = fs.createWriteStream(`${__dirname}/../dist.zip`);
  const archive = archiver('zip', {
    zlib: { level: 3 }, // 压缩层级 目前我们只有2层
  }).on('error', (err) => {
    throw err;
  });
  output.on('close', (err) => {
    if (err) {
      console.log('something error width the zip process:', err);
      return;
    }
    uploadFile();
    console.log(`${archive.pointer()} total bytes`);
    console.log('archiver has been finalized and the output file descriptor has closed.');
  });
  output.on('end', () => {
    console.log('Data has been drained');
  });
  archive.pipe(output);
  archive.directory(distPath, '/dist');
  archive.finalize();
};

// 启动 走你
zipDirector();